<template>
  <div class="upload-container" style="width: 100%;">
    <el-upload
      :show-file-list="true"
      :action="action"
      :multiple="multiple"
      :name="fileName"
      :accept="accept"
      :limit="limit"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :on-progress="onProgress"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
      :headers="uploadHeaders" 
      :data="uploadData"
    >
      <div class="upload-class">
        <img src="../../assets/img/upload.png" />
        <div>选择文件</div>
      </div>
      <template v-if="isImg" #tip>
        <span class="el-tip">支持PNG/JPG/JPEG</span>
      </template>
    </el-upload>
  </div>
</template>

<script lang="ts" setup name="SingleImageUpload">
import { reactive,computed,ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {  ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
import { getSignature } from '/@/utils';
import { deleteossfiles } from '/@/api/startfab/index';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['uploadfile']);

// 定义父组件传过来的值
const props = defineProps({
	// 列表内容
	value: {
		type: Array,
		default: () => [],
	},
  //文件名称
  fileName: {
		type: String,
		default: () => 'file',
	},
  //文件数量限制
  limit: {
		type: Number,
		default: () => 1,
	},
  //是否多选
  multiple: {
		type: Boolean,
		default: () => true,
	},
  //可选类型
  accept: {
		type: String,
		default: () => '',
	},
  //上传地址
  action: {
		type: String,
		default: () => import.meta.env.VITE_API_URL + '/admin/upload/oss',
	},
  // action: {
	// 	type: String,
	// 	default: 'https://wxxingfu.zaishengyou.com/index.php/api/upload/upload',
	// },
  //展示信息
  msg: {
		type: String,
		default: () => '',
	},
  isImg: {
		type: Boolean,
		default: () => true,
	},
  uploadData: {
    type: Object,
    default: () => ({})
  }
});
// 动态计算 headers，确保每次都能读取最新的 token
const uploadHeaders = computed(() => {
  const token = Session.get('token')
  return {
    'x-access-token': token || '',
    'X-Access-Appid': 'admin'
  }
})

// 动态上传参数（带 signature）
const uploadData = computed(() => {
  // 可以加一些业务参数
  const params = {
    // module: 'avatar',
    // from: 'user-center'
  }

  // 使用您统一的签名逻辑
  return getSignature(params)
})
 
const fileList = computed(() => {
  return props.value;
});

const handleRemove = async (file, fileList) => {
  const resData = await deleteossfiles({ files: [file.url] })
  if (resData.code == 10000) {
    emit('uploadfile', fileList)
  }
};

const handlePreview = (file) => {
  window.open(file.url);
};
const handleExceed = (files, fileList) => {
  ElMessage.error('最多上传' + props.limit + '个附件');
};

const  beforeUpload = (file) => {
  // const isIMG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
  // const isLt5M = file.size / 1024 / 1024 < 50;
  // if (!isIMG) {
  //   ElMessage.error('上传图片只能是 JPEG、JPG、PNG 格式!');
  //   return false;
  // }
  // if (!isLt5M) {
  //   ElMessage.error('上传图片大小不能超过 50MB!');
  //   return false;
  // }
  // return isIMG && isLt5M;
}

const onProgress = (event, file, fileList) => {

};

const handleSuccess = (res, file, fileList)=> {
  if (res.status === 1) {
    for (let i = 0; i < fileList.length; i++) {
      if (fileList[i]['uid'] === file['uid']) {
        fileList[i]['url'] = res.data.path;
        fileList[i]['name'] = res.data.name
        break;
      }
    }
    const urls = [];
    if (fileList.every(item => item.status == 'success')) {
      fileList.map(item => {
        urls.push(item.url);
      });
      emit('uploadfile', fileList);
    }
  } else {
    for (let i = 0; i < fileList.length; i++) {
      if (fileList[i]['uid'] === file['uid']) {
        fileList.splice(i, 1);
        break;
      }
    }
    ElMessage.error(res.msg);
  }
};

const  handleError = (err, file, fileList) =>{
  ElMessage.error(err);
};
</script>
<style scoped lang="scss">
.upload-class {
  border-radius: 6px;
  background: #F7F8FA;
  height: 32px;
  line-height: 32px;
  color: #888;
  font-family: "PingFang SC";
  font-size: 12px;
  font-style: normal;
  font-weight: 400;
  display: flex;
  align-items: center;
  padding: 0px 10px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  img {
    width: 20px;
    height: 20px;
    margin-right: 10px;
  }
}
.el-tip {
  margin-top: 0px;
}
:deep(.el-upload-list ) {
	margin-top: 0px;
  .el-upload-list__item {
    height: 20px;
    line-height: 20px;
  }
}
</style>
